<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Controller\AbstractController;
use App\Model\Admin;
use App\Request\Admin\Admin\LoginRequest;
use App\Request\Admin\Admin\RegisterRequest;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Context;

class AdminController extends AbstractController
{
    /**
     * @Inject
     * @var \Phper666\JWTAuth\JWT
     */
    protected $jwt;

    public function admin()
    {
        return $this->success(Context::get('admin'));
    }

    public function login(LoginRequest $request)
    {
        $data = $request->validated();

        $admin = Admin::where('nick_name', $data['nick_name'])->first();
        if (! $admin) {
            return $this->response->json(['code' => 404, 'message' => '用户未注册'])->withStatus(404);
        }

        if (! check($data['password'], $admin['password'])) {
            return $this->response->json(['code' => 400, 'message' => '密码错误'])->withStatus(400);
        }

        $token = $this->jwt->setScene('admin')->getToken(['id' => $admin->id, 'nick_name' => $admin->nick_name]);

        return $this->success([
            'token'  => (string) $token,
            'expire' => $this->jwt->getTTL(),
        ]);
    }

    public function register(RegisterRequest $request)
    {
        $data             = $request->validated();
        $data['password'] = bcrypt($data['password']);

        return $this->success(Admin::create($data));
    }
}
